<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container" style="margin-bottom:20px">
      <span style="margin-right:10px">发布日期：</span>
      <el-date-picker class="timeWidht" v-model="dateformat" type="daterange" align="right" unlink-panels range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd HH:mm:ss" :picker-options="pickerOptions">
      </el-date-picker>
      <span style="margin-left:10px">标题：</span>
      <el-input @keyup.enter.native="handleFilter" class="filter-item widht" placeholder="请输入关键字" v-model="listQuery.keyWord" clearable>
      </el-input>
      <span style="margin-left:10px">资讯栏目：</span>
      <el-cascader
           change-on-select clearable placeholder="请选择" expand-trigger="click"
          :options="sections"
          v-model="sectionIds"
          class="widht"
        ></el-cascader>
      <span style="margin-left:10px">资讯标签：</span>
      <el-select class="widht" v-model="listQuery.labelId" clearable filterable remote reserve-keyword placeholder="请输入标签" :remote-method="getInfoLabels">
        <el-option
          v-for="item in labels"
          :key="item.id"
          :label="item.name"
          :value="item.id">
        </el-option>
      </el-select>
      <span style="margin-left:10px">作者：</span>
      <el-input v-model="listQuery.authorName" class="widht" placeholder="请输入资讯作者" clearable></el-input>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" @click="handleAllDelete" :type="pageBoolean.delColor" icon="el-icon-delete">{{ pageBoolean.delText }}</el-button>
    </div>

    <el-table :key='tableKey' :data="list" v-loading="listLoading" element-loading-text="数据加载中，请稍后" border fit highlight-current-row :default-sort="{prop: 'inTime', order: 'descending'}" @selection-change="handleSelectionChange" @sort-change="getSortList" style="width: 100%">
      <el-table-column v-if='showAllDel' type="selection" width="55">
      </el-table-column>

      <el-table-column align="center" label="ID" min-width="95">
        <template slot-scope="scope">
          <span class="link-type">{{scope.row.id}}</span>
        </template>
      </el-table-column>

      <el-table-column min-width="240" align="center" label="标题" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{scope.row.title}}</span>
        </template>
      </el-table-column>

      <el-table-column min-width="200" align="center" label="所属栏目" show-overflow-tooltip prop="curSectionName"></el-table-column>
      <el-table-column min-width="160" align="center" label="作者" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{scope.row.authorName}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="200" align="center" label="标签" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{scope.row.labelNames}}</span>
        </template>
      </el-table-column>

      <el-table-column min-width="160" align="center" label="发布日期" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ scope.row.inTime | dateformat('YYYY-MM-DD HH:mm') }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="权重" min-width="95" 
      sortable="custom" prop="weight"></el-table-column>
      <el-table-column min-width="160" align="center" label="审核人" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{scope.row.auditName ? scope.row.auditName : scope.row.authorName}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="阅读数" min-width="95"
      sortable="custom" prop="view"></el-table-column>
      <el-table-column align="center" label="点赞数" min-width="95"
      sortable="custom" prop="likeCount"></el-table-column>

     <!--  <el-table-column align="center" label="平台" min-width="195">
        <template slot-scope="scope">
          <span class="link-type">{{scope.row.platform}}</span>
        </template>
      </el-table-column> -->

      <el-table-column align="center" label="操作" min-width="200">
        <template slot-scope="scope">
          <el-button size="small" @click="handleModifyStatus(scope.row)">编辑
          </el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div v-show="!listLoading" class="pagination-container">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.pageNo" :page-sizes="[10,20,30,50]" :page-size="listQuery.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <el-dialog top="4%" width="70%" title="编辑页" :visible.sync="dialogFormVisible">
      <el-form :rules="rules" ref="dataForm" :model="temp" label-position="left" label-width="100px" style='width: 70%; margin-left:50px;'>
        <el-form-item label="所属栏目">
          <el-cascader
             change-on-select placeholder="请选择" expand-trigger="click"
            :options="sections"
            v-model="temp.sectionIds"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input type="textarea" maxlength="100" :autosize="{ minRows: 2, maxRows: 4}" v-model="temp.title"></el-input>
        </el-form-item>
        <el-form-item label="标签">
          <multiselect style="line-height:initial" v-model="temp.labels" :options="labels" @search-change="getInfoLabels" placeholder="搜索标签" selectLabel="选择" :multiple="true" deselectLabel="删除" track-by="id" :internalSearch="false" label="name">
                <span slot='noResult'>无搜索结果</span>
              </multiselect>
          <!-- <el-tag :key="index" v-for="(tag , index) in temp.labels" closable :disable-transitions="false" @close="handleClose(tag)" type="info">
            {{tag}}
          </el-tag> -->
          <el-input class="input-new-tag" v-if="inputVisible" v-model="inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm" @blur="handleInputConfirm">
          </el-input>
          <!-- <el-button v-if="temp.labels.length != 5" class="button-new-tag" size="small" @click="showInput">新建标签</el-button> -->
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <Tinymce :height=150 ref="editor" v-model="temp.content" :value="temp.content" />
        </el-form-item>
        <el-form-item label="权重">
          <el-input-number v-model="temp.weight" :step="1"></el-input-number>
        </el-form-item>
        <el-form-item label="浏览数">
          <el-input-number v-model="temp.view" :step="1"></el-input-number>
        </el-form-item>
        <el-form-item label="点赞数">
          <el-input-number v-model="temp.likeCount" :step="1"></el-input-number>
        </el-form-item>
        <el-upload style="margin-left:10px" :headers="headers" action="/tools/oss/upload" :on-preview="handlePreview" :on-remove="handleRemove" :on-success="handleUploadSuccess" list-type="picture" :file-list="temp.file" :limit="1">
          <el-button size="small" type="primary">上传封面</el-button>
        </el-upload>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getList, delId, delIds, update, getId, getSectionCascade, getInfoLabels } from '@/api/advisory'
import { getToken } from '@/utils/auth' // 验权
import Tinymce from '@/components/Tinymce'
import Multiselect from 'vue-multiselect' // 使用的一个多选框组件，element-ui的select不能满足所有需求
import 'vue-multiselect/dist/vue-multiselect.min.css' // 多选框组件css
export default {
  name: 'list',
  components: { Tinymce, Multiselect },
  data() {
    return {
      labels:[],
      sections:[],
      sectionIds:[],
      headers: {},
      inputVisible: false,
      inputValue: '',
      brandListOptions: [],
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      dateformat: '',
      list: null,
      total: null,
      listLoading: true,
      listQuery: {
        keyWord: '',
        sectionId: null,
        labelId: null,
        pageNo: 1,
        pageSize: 10
      },
      temp: {
        sectionIds:[],
        labels: []
      },
      dialogFormVisible: false,
      rules: {
        title: [{ required: true, message: '标题必填', trigger: 'blur' }],
        'section.name': [{ required: true, message: '所属栏目必填', trigger: 'blur' }],
        'section.tab': [{ required: true, message: '标签必填', trigger: 'blur' }],
        inTime: [{ type: 'date', required: true, message: '发布日期必填', trigger: 'change' }],
        view: [{ required: true, message: '阅读数必填', trigger: 'blur' }],
        platform: [{ required: true, message: '平台必填', trigger: 'blur' }]
      },
      tableKey: 0,
      showAllDel: false,
      multipleSelection: [],
      pageBoolean: {
        delColor: 'primary',
        delText: '批量删除'
      }
    }
  },
  mounted() {
    this.getSectionCascade()
    this.getList()
    this.getInfoLabels('')
    this.headers = { accessToken: getToken() }
  },
  watch: {
    showAllDel(val) {
      if (val) {
        this.pageBoolean.delText = '选择删除';
        this.pageBoolean.delColor = 'danger';
      } else {
        this.pageBoolean.delText = '批量删除';
        this.pageBoolean.delColor = 'primary';
      }
    },
    multipleSelection(val) {
      if (val.length == 0) {
        this.pageBoolean.delText = '选择删除';
        this.pageBoolean.delColor = 'danger';
      } else {
        this.pageBoolean.delText = '确定删除';
        this.pageBoolean.delColor = 'success';
      }
    }
  },
  methods: {
    getInfoLabels(title) {
      getInfoLabels({labelName:title}).then(response => {
        const { code, data } = response
        if (code == 0) {
          this.labels = data;
        }
      })
    },
    getSectionCascade() {
      getSectionCascade().then(response => {
        const { code, data } = response
        if (code == 0) {
          this.sections = data;
        }
      })
    },
    getSortList(filed){
      let { prop, order } = filed
      let { listQuery } = this
      listQuery['sortField'] = prop
      if(prop){
        listQuery['sortWay'] = order == 'descending' ? 'DESC' : 'ASC'
      }else{
        listQuery['sortWay'] = null
      }
      this.listQuery = listQuery
      this.getList()
    },
    handleUploadSuccess(rst) {
      let { code, data: { picUrlList } } = rst;
      let { temp } = this;
      if (code == 0) {
        temp['cover'] = picUrlList[0];
      }
    },
    handlePreview(file) {},
    handleRemove(file, fileList) {
      this.temp['cover'] = '';
      this.temp['file'] = [];
    },
    handleClose(tag) {
      this.temp.labels.splice(this.temp.labels.indexOf(tag), 1);
    },

    showInput() {
      this.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        this.temp.labels.push(inputValue);
      }
      this.inputVisible = false;
      this.inputValue = '';
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleAllDelete() {
      let { showAllDel, multipleSelection } = this;
      if (multipleSelection.length != 0) {
        let ids = [];
        multipleSelection.map(e => ids.push(e.id));
        let params = { ids, operateType: 'DELETE' }
        delIds(params).then(response => {
          const { code } = response
          if (code == 0) {
            this.$notify({
              title: '成功',
              message: '批量删除资讯成功',
              type: 'success',
              duration: 2000
            })
            this.handleRefresh();
          } else {
            this.$notify({
              title: '失败',
              message: '批量删除资讯失败',
              type: 'error',
              duration: 2000
            })
          }
        })
      }
      this.showAllDel = !showAllDel;
    },
    getList() {
      this.listLoading = true;
      let params = this.listQuery;
      const { dateformat, sectionIds } = this;
      if (dateformat) {
        params['beginTime'] = dateformat[0];
        params['endTime'] = dateformat[1];
      } else {
        delete params.beginTime;
        delete params.endTime;
      }
      if(sectionIds.length>0){
        params['sectionId'] = sectionIds[sectionIds.length-1]
      }else{
        delete params.sectionId
      }
      getList(params).then(response => {
        const { code, data: { total, list } } = response;
        if (code == 0) {
          this.total = total
          this.list = list
          this.listLoading = false
        }
      });
    },
    handleFilter() {
      this.listQuery.pageNo = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.pageNo = val
      this.getList()
    },
    handleModifyStatus(row) {
      getId(row.id).then(response => {
        let { code, data } = response;
        let sectionIds = data.sectionIds.split(',');
        data.inTime = new Date(data.inTime)
        /*if (row.labelNames) {
          row.labels = row.labelNames.split(',')
        } else {
          row.labels = []
        }
        data.labels = row.labels*/
        data.file = [{ name: data.cover, url: data.cover }]
        sectionIds = sectionIds.map(e=>e=parseInt(e))
        data.sectionIds=sectionIds
        this.temp = data
        this.dialogFormVisible = true
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          let { temp, temp:{sectionIds, labels} } = this;
          if (sectionIds.length > 0){
            temp.sId = sectionIds[sectionIds.length-1]
          }
          if(labels.length > 0){
            let labelArr = []
            labels.map(e=>labelArr.push(e.id))
            temp.labels = labelArr
          }
          update(temp).then(response => {
            let { code } = response
            if (code == 0) {
              /*this.list.map((e, i) => {
                if (e.id === temp.id) {
                  temp['labelNames'] = temp['labels'].join(',')
                  temp['section'] = this.brandListOptions.filter(e => e.id == temp['sId'])[0]
                  this.list.splice(i, 1, temp)
                }
              })*/
              this.getList();
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
            }
          })
        }
      })
    },
    handleDelete(idx, row) {
      const { id } = row;
      delId(id).then(response => {
        const { code } = response
        if (code == 0) {
          this.$notify({
            title: '成功',
            message: '删除资讯成功',
            type: 'success',
            duration: 2000
          })
          const index = this.list.indexOf(idx)
          this.list.splice(idx, 1)
          this.total--
        } else {
          this.$notify({
            title: '失败',
            message: '删除资讯失败',
            type: 'error',
            duration: 2000
          })
        }
      });
    },
    handleRefresh() {
      this.list = null
      this.total = null
      this.listQuery.pageNo = 1
      this.getList()
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
.app-container {
  padding: 20px;
}
.pagination-container {
  margin-top: 30px;
}
.widht{
  width: 180px;
}
.timeWidht{
  width: 300px;
}
</style>